<template>
	<view>
		<u-upload :fileList="fileList5" @afterRead="afterRead" @delete="deletePic" name="5" multiple :maxCount="maxCount" width="110" height="110">
			<image src="../../static/images/icon/bg_upload_img.png" style="width: 110px; height: 110px" mode=""></image>
		</u-upload>
	</view>
</template>

<script>
import md5 from 'js-md5';
export default {
	name: 'uploadImage',
	props: {
		maxCount: {
			type: Number,
			default: 3
		}
	},
	data() {
		return {
			fileList5: []
		};
	},
	methods: {
		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1);
			this.$emit('success', this.fileList5);
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists.map(item => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url);
				let item = this[`fileList${event.name}`][fileListLen];
				this[`fileList${event.name}`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					})
				);
				fileListLen++;
			}
			this.$emit('success', this.fileList5);
		},
		async uploadFilePromise(url) {
			let token = await this.$helper.getQiniuToken();
			let key = 'mp-weixin/uploads/' + md5(url);

			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: 'https://up-z0.qiniup.com',
					filePath: url,
					name: 'file',
					formData: {
						key,
						token
					},
					success: uploadFileRes => {
						if (uploadFileRes.errMsg == 'uploadFile:ok') {
							let data = JSON.parse(uploadFileRes.data);
							resolve(data.key);
						} else {
							reject('上传失败,请稍后重试!');
						}
					},
					fail(err) {
						reject('上传失败,请稍后重试!');
					}
				});
			});
		}
	}
};
</script>

<style lang="scss">
/deep/ .u-upload__wrap__preview {
	&:nth-child(3n) {
		margin-right: 0;
	}
}
</style>
